package com.remoting.tools;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Token 工具类
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年3月20日下午4:37:44
 */
public class TokenUtils {
	public static String encodeBase64URLSafeString(String data) throws UnsupportedEncodingException {
        String base64str = Base64.encodeBase64String(data.getBytes());
        if (base64str.contains("+")) {
            base64str = base64str.replaceAll("\\+", "-");
        }
        if (base64str.contains("/")) {
            base64str = base64str.replaceAll("/", "_");
        }

        return base64str;
    }
	
	public static String hmacSha1Base64UrlSafe(String data, String key) throws UnsupportedEncodingException {
        byte[] hmacSha1 = hmacSha1(data, key);
        return encodeBase64URLSafeString(hmacSha1);
    }
	
	public static byte[] hmacSha1(String data, String key) {
        byte[] byteHMAC = null;
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            mac.init(spec);
            byteHMAC = mac.doFinal(data.getBytes());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException ignore) {
        }
        return byteHMAC;
    }
	
	public static String encodeBase64URLSafeString(byte[] bytes) throws UnsupportedEncodingException {
        String base64str = Base64.encodeBase64String(bytes);
        if (base64str.contains("+")) {
            base64str = base64str.replaceAll("\\+", "-");
        }
        if (base64str.contains("/")) {
            base64str = base64str.replaceAll("/", "_");
        }
        return base64str;
    }
	
	public static String generatToken(String apiKey, String secretKey, Policy policy) throws UnsupportedEncodingException {
        StringBuffer token = new StringBuffer(encodeBase64URLSafeString(apiKey));
        token.append(":");
        token.append(hmacSha1Base64UrlSafe(encodeBase64URLSafeString(JSONObject.toJSONString(policy)), secretKey));
        token.append(":");
        token.append(encodeBase64URLSafeString(JSONObject.toJSONString(policy)));
        return token.toString();
    }
	/**
	 * 生成accesstoken
	 * <p>说明:</p>
	 * <li></li>
	 * @param appKey 应用的唯一标示
	 * @param secretKey 安全码
	 * @param scope 作用域
	 * @param api 接口
	 * @return
	 * @since 2017年3月20日下午4:39:37
	 */
	public static String genToken(String appKey, String secretKey,String scope,String api){
		Policy policy = new Policy();
        Date date = new Date();
        Date ex = new Date(date.getTime() + 1000 * 3600 * 24);
        policy.setScope(scope);
        policy.getApis().add(api);
        policy.setExpiredTime(ex);
        try {
			return TokenUtils.generatToken(appKey, secretKey, policy);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        return "";
	}
	public static void main(String[] args) throws UnsupportedEncodingException{
		String accesstoken = TokenUtils.genToken("p16gs674", "k8727g76hbdsg41chfuw8cc0ad26rae2","USER", "isExisted");
        System.out.println(accesstoken);
	}
}
